<template>
  <div class="history-record">
    <div class="history-head">
      <el-button icon="el-icon-search" @click="backListAll()"> 返回 </el-button>
    </div>
    <div id="mapbox3" v-loading="loading" element-loading-text="拼命加载中">
      <div class="map-info">
        <div class="positiondiv"><span /></div>
        <div class="scalediv"><span /></div>
      </div>
      <!-- 地图容器 -->
      <div id="map" style="height: 700px; width: 100%" />

      <div class="tooltip">
        <el-row class="toolrow" :gutter="20">
          <el-col :span="1">
            <!-- 播放暂定按钮 -->
            <el-tooltip :content="playbtnTooltip" placement="top">
              <el-button
                ref="playbtn"
                class="play-pause-but playbtn"
                type="primary"
                icon="al-icon-carplay"
                size="mini"
                circle
                @click="clickPlayBtn"
              />
            </el-tooltip>
          </el-col>
          <el-col :span="16">
            <!-- 进度滑块 -->
            <div class="progress_slider">
              <el-slider
                v-model="progressIndex"
                :max="progressMax"
                :format-tooltip="formatProgressTooltip"
                @change="progressValueChange"
              />
            </div>
          </el-col>
          <el-col :span="3">
            <!-- 速度滑块 -->
            <div class="speed_slider">
              <span>{{ $t("history.speed") }}</span>
              <el-select v-model="speedIndex" style="width: 80px">
                <el-option
                  v-for="item in speedIndexs"
                  :key="item.speed"
                  :label="item.label"
                  :value="item.speed"
                />
              </el-select>
            </div>
          </el-col>
          <el-col :span="3">
            <!-- 进度滑块 -->
            <!-- 显示当前点时间 -->
            <div class="historytime">
              <span id="Tagtime" />
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import {
  Load_Map,
  TagStyle,
  _TransMetric,
  _TransPixel,
  _dPR,
  _iMap,
  t,
  setMapCenter,
  FenceLayer,
  FenceSource,
  LoadTypeData,
  sendThis
} from '@/utils/iMap.js'
import { Vector as VectorLayer } from 'ol/layer.js'
import { Vector } from 'ol/source.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import Feature from 'ol/Feature.js'
import { Fill, Stroke, Style, Text, Icon } from 'ol/style.js'

import { baseUrl } from '@/utils/global.js'
import {
  getListData,
  confirmAlarm,
  getMap,
  getHistoryInfoDetail
} from '@/api/cy.js'

export default {
  props: {
    idx: {
      type: String,
      required: true
    },
    objParam: {
      type: Object,
      required: true,
      default() {
        return {}
      }
    }
  },

  data() {
    return {
      loading: true,
      paramObj: this.objParam,
      idxId: this.idx,

      param: {}, // 请示历史轨迹是的参数
      showDetail: false, // 显示详情
      timeoutIndex: null,
      playbtnTooltip: '暂停',
      progressIndex: 0, // 播放进度位置
      progressLimitIndex: 0,
      lineSource: null, // 标签资源容器
      trackData: [],
      progressMax: 0, // 播放进度最大值
      speedIndex: 2,
      speedIndexs: [
        { speed: 1, label: 'x1' },
        { speed: 2, label: 'x2' },
        { speed: 4, label: 'x4' },
        { speed: 8, label: 'x8' },
        { speed: 16, label: 'x16' }
      ],
      currentMapId: null,
      styles: {
        linestring: new Style({
          stroke: new Stroke({
            color: 'green',
            width: 3
          }),
          zIndex: 999
        }),
        geoMarker: new Style({
          image: new Icon({
            offset: [0, 0],
            size: [22, 30],
            // src: "../../static/img/icon/5ren.png",
            src: require('../../../../assets/images/5ren.png'),
            color: '#8959A8',
            opacity: 1
          }),
          zIndex: 10000
        }),
        point: new Style({
          image: new Circle({
            radius: 5,
            snapToPixel: false,
            fill: new Fill({
              color: 'red'
            }),
            stroke: new Stroke({
              color: 'white',
              width: 1
            })
          })
        })
      }
    }
  },
  watch: {
    idx(value, oldvalue) {
      // console.log('监听layerid变化', value, oldvalue)
      this.currentMapId = value
      this.idxId = value
      s
      //   this.currentMapId=value;
    },
    objParam(value, oldvalue) {
      // console.log('监听对象变化', value, oldvalue)
      this.paramObj = value
    }
  },
  mounted() {
    setTimeout(() => {
      if (this.loading) {
        this.loading = false
      }
    }, 8000)
  },
  destroyed() {
    this.closeDialog()
  },

  methods: {
    backListAll() {
      this.$emit('changeChakan', false)
    },
    formatProgressTooltip(val) {
      // if (this.trackData[val].speed) {
      //   return this.trackData[val].speed;
      // }
      // return '';
    },
    openDialogCallBack() {
      console.log('调用回调')
    },

    // 请求历史轨迹详情数据，加载地图，渲染轨迹
    loadMapAndTrack() {
      // console.log(
      //   '监听对象内容',
      //   this.currentMapId,
      //   this.objParam,
      //   this.idx,
      //   this.idxId,
      //   this.paramObj
      // )
      const self = this
      self.progressIndex = 0 // 防止没有查到数据时，无法置零
      if (!self.idxId) {
        this.msgInfo('抱歉，id值丢失了哈哈哈')
        return
      }
      getMap(self.idxId).then((res) => {
        this.loading = false
        const RES = self.responseUse(res)
        if (undefined != RES) {
          Load_Map(
            baseUrl + RES.mapPath,
            RES.mapActualX,
            RES.mapActualY,
            RES.mapPixelX,
            RES.mapPixelY,
            RES.mapPixelX / RES.mapActualX,
            [RES.mapOriginX, RES.mapOriginY]
          )

          const param = {
            resourceId: '020E1A',
            startTime: '2021-05-21 18:04:26',
            endTime: '2021-05-21 18:06:26',
            mapId: 177
          }

          getHistoryInfoDetail(this.paramObj).then((res) => {
            const RES = self.responseUse(res)
            if (undefined != RES) {
              if (RES.length > 0) {
                self.trackData = RES

                if (self.trackData.length > 1) {
                  self.progressMax = self.trackData.length - 1
                } else {
                  self.progressMax = 1
                }
                console.log(
                  '索引：',
                  self.progressIndex,
                  '最大值：',
                  self.progressMax
                )

                self.initData()

                if ($('.playbtn i').attr('class') === 'al-icon-carplay') {
                  // 处于暂定状态
                  $('.playbtn i').attr('class', 'al-icon-carpause')
                  self.playbtnTooltip = '暂停'
                }
              } else {
                self.v_MyMessage(self.$t('Notice.noTrackDetails'), 'warning')
              }
            }
          })
        }
      })
    },

    // 往地图容器
    initData: function() {
      // 移除标签层信息
      _iMap.removeLayer(this.lineLayer)
      // 每次进入不管是否切换查看的详情数据
      // 都将地图中的数据清空

      if (this.lineSource == null) {
        this.lineSource = new Vector({
          wrapX: false
        })
      }

      if (this.lineLayer == null) {
        this.lineLayer = new VectorLayer({
          minResolution: 0,
          maxResolution: _dPR * 2.4,
          source: this.lineSource,
          zIndex: 10000,
          renderBuffer: 100,
          updateWhileAnimating: true,
          updateWhileInteracting: true,
          style: function(feature, resolution) {
            return TagStyle(feature, resolution)
          }
        })
      }

      _iMap.addLayer(this.lineLayer)

      // 往地图中加载轨迹数据
      this.progressIndex = 0
      this.drawLine()
    },

    // 绘制线
    drawLine() {
      let lineFeature
      let to
      let markPoint
      let markFeature
      const from = [
        this.trackData[this.progressIndex].posX,
        this.trackData[this.progressIndex].posY
      ]
      if (this.progressIndex === this.trackData.length - 1) {
        to = from
        $('#Tagtime').text(this.trackData[this.progressIndex].speed)
      } else {
        const toIndex = this.progressIndex + 1
        to = [this.trackData[toIndex].posX, this.trackData[toIndex].posY]
        $('#Tagtime').text(this.trackData[toIndex].speed)
      }

      // 画点
      const coords = [_TransPixel(from), _TransPixel(to)]
      if (this.progressIndex === 0) {
        const first = [this.trackData[0].posX, this.trackData[0].posY]
        markPoint = new Point(_TransPixel(first))
      } else {
        // alert(this.progressIndex)
        markPoint = new Point(_TransPixel(to))
      }
      markFeature = new Feature(markPoint)
      // 画线
      lineFeature = new Feature(new LineString(coords))
      lineFeature.setStyle(this.styles.linestring)
      this.lineSource.addFeature(lineFeature)

      // 定时划线到地图中去
      if (this.progressIndex < this.trackData.length - 1) {
        const self = this
        this.progressIndex++
        let temp
        if (self.speedIndex === 0) {
          temp = 300 * 2
        } else {
          temp = (300 / self.speedIndex).toFixed()
        }
        if (this.progressIndex < this.progressLimitIndex) {
          self.drawLine()
        } else {
          self.timeoutIndex = setTimeout(function() {
            self.drawLine()
          }, temp)
        }
      }

      const toObj = this.lineSource.getFeatureById('to')

      if (toObj != null) {
        // 已经添加过
        toObj.getGeometry().setCoordinates(_TransPixel(to))
      } else {
        markFeature.setId('to')
        markFeature.setStyle(this.styles.geoMarker)
        this.lineSource.addFeature(markFeature)
      }
    },

    // 进度条发生变化时的回调函数
    progressValueChange(val) {
      this.progressIndex = 0
      this.progressLimitIndex = parseInt(val)

      clearTimeout(this.timeoutIndex)
      this.clearMap()
      this.drawLine()
    },
    // 清除地图中的数据
    clearMap() {
      if (this.lineSource != null) {
        const self = this
        self.lineSource.forEachFeature(function(feature) {
          self.lineSource.removeFeature(feature)
        })
        // _iMap.removeLayer(self.lineLayer);
      }
    },

    // 播放按钮响应
    clickPlayBtn() {
      clearTimeout(this.timeoutIndex)
      const className = $('.playbtn i').attr('class')

      if (className === 'al-icon-carplay') {
        // 处于暂定状态
        $('.playbtn i').attr('class', 'al-icon-carpause')
        this.playbtnTooltip = '暂停'
        // 播放
        this.drawLine()
      } else if (className === 'al-icon-carpause') {
        // 处于播放状态
        $('.playbtn i').attr('class', 'al-icon-carplay')
        this.playbtnTooltip = '播放'
        // 暂停
      }
    },

    /**
     * 关闭dialog时的回调函数
     */
    closeDialog() {
      this.clearMap()
      clearTimeout(this.timeoutIndex)

      if ($('.playbtn i').attr('class') === 'al-icon-carpause') {
        $('.playbtn i').attr('class', 'al-icon-carplay')
        this.playbtnTooltip = '播放'
      }
      this.trackData = []
      this.progressIndex = 0
      this.progressLimitIndex = 0
    }
  }
}
</script>

<style lang="scss" scoped>
.history-record {
  width: 100%;
  height: 100%;
}
.history-head {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.tooltip {
  box-sizing: border-box;
  padding: 10px;
}
#mapbox3 {
  position: relative;
}

.map-info {
  color: gray;
  position: absolute;
  right: 10px;
  background: #ffffffc4;
  z-index: 10;
  padding: 10px;
  border-radius: 8px;
}
.scalediv {
  height: 9px;
  margin-top: 20px;
  border-left: gray solid 1px;
  border-bottom: gray solid 1px;
  border-right: gray solid 1px;
  position: relative;
}
.scalediv span {
  display: inline-block;
  width: 100%;
  text-align: center;
  position: absolute;
  top: -13px;
}
.play-pause-but {
  width: 40px;
  height: 40px;
  padding: 10px;
}
</style>
